<template>
  <a-modal
    :open="open"
    width="1200px"
    :title="rowData.txm ? '修改医技申请单' : '新增医技申请单'"
    centered
    :keyboard="false"
    :ok-button-props="{ disabled: !isCompleted }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-radio-group v-model:value="formState.applyPath" button-style="solid" class="ml-20 mb-3" @change="onChangeActive">
      <a-radio-button :value="0">门诊</a-radio-button>
      <a-radio-button :value="1">住院</a-radio-button>
    </a-radio-group>
    <a-form :model="formState" class="flex justify-between" :colon="false" :label-col="{ style: { width: '78px' } }">
      <a-form-item label="姓名" name="brName" class="w-[500px]" v-bind="validateInfos.brName">
        <SelectTable
          v-if="formState.applyPath === 0"
          v-model:value="formState.brName"
          type="检验患者"
          :search-params="{ stdate: dayjs().format('YYYY-MM-DD'), eddate: dayjs().format('YYYY-MM-DD') }"
          @select="(row) => onSelect(row)"
        />
        <SelectTable v-else v-model:value="formState.brName" type="押金检索收取押金" @select="(row) => onSelect(row)" />
      </a-form-item>
      <a-form-item name="stdate" label="检查日期">
        <a-date-picker v-model:value="formState.examDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
      </a-form-item>
    </a-form>
    <div style="margin-left: 76px">
      <div class="card-box flex flex-wrap justify-between">
        <a-card class="card-item active" :body-style="{ padding: 0 }" hoverable>
          <div class="item-header">
            <a-avatar class="ml-2" :src="avatarMan" />
            <div class="flex-1 ml-5 flex justify-between items-center">
              <div class="flex justify-between items-center w-[150px]">
                <div class="font-semibold">
                  {{ userData?.brName || '-' }}
                </div>
                <div>
                  {{ userData?.brXb || '-' }}
                </div>
                <div>{{ userData?.brAge || '-' }}</div>
              </div>
              <div class="min-w-20">
                {{ userData?.brMob || '-' }}
              </div>
              <div class="min-w-20">
                <span>{{ userData?.brId || '-' }}</span>
              </div>
              <div class="min-w-20">
                <span>{{ userData?.bcLczdZdmc || '-' }}</span>
              </div>
              <div class="min-w-20">
                <span>{{ userData?.brFzrName || userData?.lastAttendingDoctorName || '-' }}</span>
              </div>
              <div class="min-w-20">
                <span>{{ userData?.ksmc || '-' }}</span>
              </div>
              <template v-if="formState.applyPath === 1">
                <div class="min-w-20">
                  <span>{{ userData?.wardName || '-' }}</span>
                </div>
                <div class="min-w-20">
                  <span>{{ userData?.bedcode || '-' }}</span>
                </div>
              </template>
            </div>
          </div>
        </a-card>
      </div>
    </div>
    <div class="flex mt-4">
      <div class="w-[350px]" style="margin-left: 76px">
        <BaseTable
          column-code="001097"
          :data-source="tableData"
          :custom-row="onClickRow"
          :row-class-name="(record) => (record.categoryCode === categroyRow.categoryOne ? 'selected-row' : '')"
          :scroll="{ y: 400 }"
          :height="400"
          :loading="loading"
        >
          <template #bodyCell="{ column, index }">
            <template v-if="column.dataIndex == 'xh'">
              {{ index + 1 }}
            </template>
          </template>
        </BaseTable>
      </div>
      <div class="w-[350px] ml-4">
        <BaseTable
          column-code="001098"
          row-key="orderItemCode"
          :data-source="projectData"
          :custom-row="onClickRowPart"
          :row-class-name="(record) => (record.orderItemCode === categroyRowProject.orderItemCode ? 'selected-row' : '')"
          :scroll="{ y: 400 }"
          :height="400"
          :loading="loadingProject"
          :row-selection="rowSelection"
        />
      </div>
      <div class="w-[345px] ml-4">
        <BaseTable
          column-code="001099"
          row-key="partKey"
          :data-source="categroyRowProject.partList"
          :scroll="{ y: 400 }"
          :height="400"
          :row-selection="rowSelectionPart"
        />
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import SelectTable from '@/components/SelectTable'
import { post } from '@/utils/request'
import useAppStore from '@/store/user'
import avatarMan from '@/assets/images/avatar-man.png'

const storeUser = useAppStore()
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({ brName: '', applyPath: 0 })
const userData = ref({})
const categroyRow = ref({})
const categroyRowProject = ref({})
// const categroyRowPart = ref({})
const selectedRowKeys = ref([])
const selectedRowKeysPart = ref([])
const selectedRows = ref([])
const selectedRowsPart = ref([])
// const partProjectData = ref([])
const emit = defineEmits(['update:open', 'success'])
const rulesState = ref({
  brName: [{ required: true, message: '请选择' }]
  // applyDoctorId: [{ required: true, message: '请选择' }]
})
const { isCompleted, validateInfos } = useForm(formState, rulesState)

const onChangeActive = () => {
  userData.value = {}
  formState.value.brName = ''
}

// 医技分类
const { loading, getData, tableData } = useTable({
  url: '/ris/dictCategory/getDictCategoryListByEmp',
  formatResult: (data) => {
    categroyRow.value = data.length ? data[0] : {}
    categroyRow.value.categoryOne = formState.value.categoryCode || data[0]?.categoryCode
    categroyRow.value && getProjectData()
    return data
  }
})
// 项目名称
const {
  loading: loadingProject,
  getData: getProjectData,
  tableData: projectData
} = useTable({
  url: '/ris/dictCategory/getDictCategoryItemList',
  formatParams: () => {
    return {
      data: categroyRow.value.categoryOne,
      appSn: formState.value.appSn
    }
  },
  formatResult: (data) => {
    if (data.length > 0) {
      categroyRowProject.value = data[0]
      // categroyRowProject.value.orderItemCode = formState.value.orderItemCode || data[0]?.orderItemCode
      data.forEach((item, index) => {
        if (item.isSelected === 1) {
          selectedRows.value.push(item)
          selectedRowKeys.value.push(item.orderItemCode)
        }
        if (formState.value?.appSn) {
          if (item.partList?.length > 0) {
            item.partList.forEach((part) => {
              part.partKey = item.orderItemCode + part.key
              if (part?.isSelected === 1) {
                selectedRowsPart.value.push(part)
                selectedRowKeysPart.value.push(part.partKey)
              }
            })
          }
        } else {
          if (index === 0) {
            item?.partList?.forEach((item) => {
              item.isSelected = true
              selectedRowsPart.value.push(item)
              selectedRowKeysPart.value.push(item.partKey)
            })
          }
        }
      })
    } else {
      selectedRowKeysPart.value = []
      selectedRowsPart.value = []
    }

    return data
  }
})

// 项目名称
const rowSelection = ref({
  checkStrictly: true,
  selectedRowKeys: selectedRowKeys,
  onChange: (keys, rows) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  },
  // 所有列
  // onSelectAll: (selected, rows) => {
  //   selectedRows.value = rows
  // },
  onSelect: (record, selected) => {
    record.isSelected = selected
    record?.partList?.forEach((item) => {
      item.isSelected = true
      selectedRowsPart.value.push(item)
      selectedRowKeysPart.value.push(item.partKey)
    })
    selected && onSelectItem(record)
  }
})

// 检查部位
const rowSelectionPart = ref({
  checkStrictly: true,
  selectedRowKeys: selectedRowKeysPart,
  onChange: (keys, rows) => {
    selectedRowKeysPart.value = keys
    selectedRowsPart.value = rows
  },
  onSelect: (record, selected) => {
    record.isSelected = selected
  }
})

// 选择名称
const onSelect = (row) => {
  userData.value = row
  formState.value.brName = row.brName
  formState.value.brId = row.brId
  formState.value.key = row.jzbh || row.inplsh
  formState.value.bcLczdZddm = row.bcLczdZddm ?? row.icd10Code
  formState.value.applyDeptCode = row.ksdm ?? row.lastDeptCode
}

// 医技分类点击
const onClickRow = (record) => {
  return {
    onClick: () => {
      categroyRow.value = record
      categroyRow.value.categoryOne = record.categoryCode
      selectedRowKeys.value = []
      selectedRows.value = []
      getProjectData()
    }
  }
}

const onSelectItem = (record) => {
  categroyRowProject.value = record
  // selectedRowsPart.value = []
  // partProjectData.value = []
  // selectedRowKeysPart.value = [] // 清楚检查部位选项
  // if (record?.partList.length > 0) {
  //   partProjectData.value = record.partList
  //   selectedRowKeysPart.value = record.partList.map((item) => {
  //     return item.key
  //   })
  //   partProjectData.value.forEach((item) => {
  //     selectedRowsPart.value.push(item)
  //   })
  // }
}
// 项目名称点击
const onClickRowPart = (record) => {
  return {
    onClick: () => onSelectItem(record)
  }
}

const onOk = async () => {
  if (selectedRowKeys.value.length === 0) return message.error('请选择项目')
  const arr = projectData.value.map((item) => {
    if (item.isSelected) {
      return {
        orderItemCode: item.orderItemCode,
        orderItemName: item.orderItemName,
        partCode: onPartSelected(item)
      }
    }
  })
  const applyItemList = arr.filter((item) => {
    return item !== undefined
  })

  const { code, msg } = await post('/ris/apply/doSaveApply', {
    ...categroyRow.value,
    ...formState.value,
    applyItemList: applyItemList,
    brId: formState.value.brId,
    applyPath: formState.value.applyPath,
    confEmpId: storeUser.empId,
    key: formState.value?.key
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  onReset()
  emit('update:open', false)
  emit('success')
}

const onPartSelected = (row) => {
  const arr = row.partList.filter((item) => {
    return item.isSelected
  })
  return arr
    .map((item) => {
      return item.key
    })
    .join(',')
}

const onReset = () => {
  formState.value = {}
  userData.value = {}
  categroyRow.value = {}
  categroyRowProject.value = {}
  selectedRowKeys.value = []
  selectedRows.value = []
  selectedRowsPart.value = []
  selectedRowKeysPart.value = []
}

const onCancel = () => {
  onReset()
  emit('update:open', false)
}
watch(
  () => props.open,
  async (val) => {
    if (val) {
      formState.value = {
        ...props.rowData,
        brName: props.rowData?.brName || '',
        applyPath: props.rowData?.applyPath || 0,
        examDate: props.rowData?.applyTime || dayjs().format('YYYY-MM-DD')
      }
      userData.value = { ...props.rowData }
      await getData()
      // categroyRow.value.categoryOne = props.rowData.categoryCode || categroyRow.value.categoryCode
      // categroyRowPart.value.categroyCodePart = props.rowData.categroyCodePart || categroyRowPart.value.categroyCodePart
    }
  }
)
</script>
<style lang="less" scoped>
.card-box {
  overflow: hidden auto;
  .card-item {
    width: 100%;
    height: fit-content;
    &.active {
      border: 1px solid var(--primary-color);
      .item-header {
        color: #fff;
        background-color: var(--primary-color);
        .font-semibold {
          font-size: 18px;
        }
      }
    }
    .item-header {
      position: relative;
      display: flex;
      padding: 8px;
      background-color: #00000010;
    }
  }
}
</style>
